package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.config.WechatAccountConfig;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.lock.domain.AWechatMiniProgramUsers;
import com.ruoyi.lock.mapper.AWechatMiniProgramUsersMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.utils.login.WeChatRequestUtil;
import com.ruoyi.wechat.domain.WeChatAuthorizedLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


/**
 * 用户登录
 * 
 * @author MubaiClink
 * @date 2024-03-07
 */
@Anonymous
@RestController
@RequestMapping("/wechat/Login")
public class WechatUserLoginController extends BaseController
{
    @Autowired
    private WechatAccountConfig wechatAccountConfig;
    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private AWechatMiniProgramUsersMapper aWechatMiniProgramUsersMapper;
 ;

    /**
     * 用户登录
     * @param weChatAuthorizedLoginVo
     * @return
     */
    @Anonymous
    @PostMapping("/weChatAuthorizedLogin")
    public AjaxResult weChatAuthorizedLogin(@RequestBody WeChatAuthorizedLoginVo weChatAuthorizedLoginVo) {
        //获取openID、sessionKey
        Map map = WeChatRequestUtil.getSessionKey(wechatAccountConfig.getAppId(),wechatAccountConfig.getMpczAppSecret(),weChatAuthorizedLoginVo.getJsCode());
        logger.info("微信获取的SessionKey返回={}",map);
        String openid = map.get("openid").toString();
        String sessionKey = map.get("session_key").toString();
        String unionid = map.get("unionid").toString();
        AWechatMiniProgramUsers aWechatMiniProgramUsers = new AWechatMiniProgramUsers();
        aWechatMiniProgramUsers.setOpenid(openid);
        /*查询小程序信息*/
        AWechatMiniProgramUsers aWechatMiniProgramUsers1 = aWechatMiniProgramUsersMapper.selectAWechatMiniProgramUsers(aWechatMiniProgramUsers);
        if (aWechatMiniProgramUsers1 !=null){
                return  AjaxResult.success("你还没有办理入住");

        }else{
            return  AjaxResult.success("您没有办理入住");
        }


    }
    @Anonymous
    //页面授权用
    @PostMapping("/weChatAuthorizedLogin2")
    public AjaxResult weChatAuthorizedLogin2(@RequestBody WeChatAuthorizedLoginVo weChatAuthorizedLoginVo) {
        //获取openID、sessionKey
        Map map = WeChatRequestUtil.getSessionKey(wechatAccountConfig.getAppId(),wechatAccountConfig.getMpczAppSecret(),weChatAuthorizedLoginVo.getJsCode());
        String openid = map.get("openid").toString();
        map.put("openid",openid);
        return AjaxResult.success(map);
    }
    @Anonymous
    @PostMapping("/getWxUser")
    public AjaxResult getWxUser(@RequestBody WeChatAuthorizedLoginVo weChatAuthorizedLoginVo) {
        //获取openID、sessionKey
        Map map = WeChatRequestUtil.getSessionKey(wechatAccountConfig.getAppId(),wechatAccountConfig.getMpczAppSecret(),weChatAuthorizedLoginVo.getJsCode());
        logger.info("微信获取的SessionKey返回={}",map);
        String openid = map.get("openid").toString();
        String sessionKey = map.get("session_key").toString();
        String uniCode = map.get("unionid").toString();

        /*查询小程序信息*/
        map.put("openid", openid);
        map.put("uniCode", uniCode);

        try{
            AWechatMiniProgramUsers aWechatMiniProgramUsers = new AWechatMiniProgramUsers();
            aWechatMiniProgramUsers.setOpenid(openid);
            aWechatMiniProgramUsers.setUnionid(uniCode);
            aWechatMiniProgramUsersMapper.insertAWechatMiniProgramUsers(aWechatMiniProgramUsers);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        return AjaxResult.success(map);
    }

    /**
     * 绑定微信用户
     * @param
     * @return
     */
    @Anonymous
    @PostMapping("/loginByPhone")
    public AjaxResult loginByPhone(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = null;
        SysUser sysUsers = userService.selectUserByUserPhone(loginBody.getUsername());
        if (sysUsers == null){
            ajax= AjaxResult.error("管理员没给你开通账号,或者账号已被绑定");
        }else{
            SysUser sysUser = new SysUser();
            sysUser.setUserId(sysUsers.getUserId());
            sysUser.setOpenid(loginBody.getOpenid());
            sysUserMapper.updateUser(sysUser);
            // 生成令牌
            String token = loginService.login(sysUsers.getUserName(), loginBody.getPassword(), loginBody.getCode(),
                    loginBody.getUuid());
            ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);

        }

        return ajax;
    }



}
